
// todo:
// 1.promise化
// 2.proxy化
// 3.解构

const md5 = require('md5_fyb.js')

// 公共方法
function isEmptyObject(e) {
  let t;
  for (t in e)
    return !1;
  return !0
}

// 模拟对话框（确定，取消）

function showModal_ (title, content, fText, yText, showCancel) {
  return new Promise(function (resolve, reject) {
    wx.showModal({
      title: title,
      content: content,
      cancelText: fText, // 取消按钮的文字  
      confirmText: yText, // 确认按钮文字  
      showCancel: showCancel, // 是否显示取消按钮，默认为 true
      confirmColor: '#FFAA01',
      cancelColor: '#c1c1c1',
      success (res) {
        return resolve(res.confirm)
      }
    })
  })
}

function showModal (title) {
  return new Promise(function (resolve, reject) {
    wx.showModal({
      title: '提示',
      content: title,
      success (res) {
        return resolve(res.confirm)
      }
    })
  })
}

// 显示成功弹窗
function showSuccessToast(title) {
  wx.showToast({
    title: title,
    duration: 1500
  })
}

// 显示失败弹窗
function showFailedToast(title, imgUrl) {
  wx.showToast({
    title: title,
    icon: 'none',
    image: imgUrl,
    duration: 1500
  })
}

// 显示等待弹窗
function showLoadingToast(title = '加载中', isShow = true) {
  if (isShow) {
    wx.showLoading({
      title: title,
      mask: true,
    })
  } else {
    wx.hideLoading()
  }
}

// 微信登录
function wxLogin() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        resolve(res)
      },
      error: function (res) {
        reject(res)
      }
    })
  })
}

// 预处理请求参数
function paramsAssemble_tvpai(paramsObj = {}) {
  let vuid = wx.getStorageSync("wxopenid")
  if (vuid === "" || vuid == null) {
    vuid = "1111";//无实际意义，传空会报错
  }
  let orignParams = {
    "appkey": '5cc090ddad6e4544815a0026e9a735a4',
    "time": Math.round(new Date().getTime() / 1000).toString(),
    "tv_source": getTvsource(),
    "version_code": 33,
    // 'token': 'fanyanbo',
    "vuid": vuid
  }
  let desParams = Object.assign(orignParams, paramsObj);
  // console.log(desParams);
  let desArray = Object.keys(desParams).sort();
  // console.log(desArray);
  let desSortedParams = {};
  // 注意中文编码
  for (let i in desArray) {
    // desSortedParams[desArray[i]] = encodeURIComponent(desParams[desArray[i]]);
    desSortedParams[desArray[i]] = desParams[desArray[i]];
  }
  let signStr = sign_tvpai(desSortedParams, 'cd8a62acc6164b27a9af4d29de8eeebd');
  // console.log(signStr);
  desSortedParams["sign"] = signStr;
  return desSortedParams;
}
// 处理url参数
function urlAssemble_tvpai(url, params) {
  if (isEmptyObject(params)) {
    return url;
  } else {
    let result = '?';
    for (let key in params) {
      if (params[key] == null || params[key] === "") continue;
      result += key + '=' + params[key] + '&';
    }
    let paramsStr = result.substr(0, result.length - 1);
    return url + paramsStr;
  }
}

// 以微信后台规则进行签名
function sign_wx(str, k) {
  var paramsStr = setParams_wx(str);
  var signedStr = md5.MD5(paramsStr + k);
  // console.log(paramsStr + k, signedStr);
  return signedStr;
}

function setParams_wx(params) {
  if (isEmptyObject(params)) {
    return "";
  } else {
    var result = '';
    for (var key in params) {
      if (params[key] === null || params[key] === "") continue;
      result += key + '=' + params[key] + '&';
    }
    return result.substr(0, result.length - 1);
  }
}

// 注意少军后台接口，需要对传入参数进行排序
function paramsAssemble_wx(paramsObj = {}) {
  // let paramsStr = paramsObj;
  // 需要对paramsObj进行排序
  let desArray = Object.keys(paramsObj).sort();
  let desSortedParams = {};
  for (let i in desArray) {
    desSortedParams[desArray[i]] = paramsObj[desArray[i]];
  }
  let signedStr = sign_wx(desSortedParams, '9acd4f7d5d9b87468575b240d824eb4f');
  let orignParams = {
    client_id: 'applet',
    sign: signedStr,
    param: desSortedParams
  };
  let desParams = Object.assign(orignParams, paramsObj);
  return desParams;
}

// 封装接口请求
function request(url, method, params, success, fail, complete) {
  wx.request({
    url: url,
    data: params,
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: method,
    success: function (res) {
      if (res.statusCode == 200) {
        return typeof success == 'function' && success(res)
      }
    },
    fail: function () {
      return typeof fail == 'function' && fail()
    },
    complete: function (res) {
      return typeof complete == 'function' && complete(res)
    },
  })
}

function requestP(url, params, method = 'GET', contentType = 'application/x-www-form-urlencoded') {
  return new Promise(function (resolve, reject) {
    wx.showLoading({
      title: '拼命加载中',
    })
    wx.request({
      url: url,
      data: params,
      header: {
        'Content-Type': contentType
        // 这里可定义访问令牌和登录令牌
      },
      method: method,
      success: function (res) {
        wx.hideLoading()
        if (res.data.code !== 200) {
          if (res.data || res.data.message) {
            showFailedToast(res.data.message)
          } else {
            showFailedToast('服务器忙，请稍后重试')
          }
          reject({ error: '服务器忙，请稍后重试', code: 500 });
          return;
        }
        resolve(res);
      },
      fail(res) {
        wx.hideLoading()
        reject(res);
        showFailedToast('请稍后重试')
      },
      complete: function (res) {
        // noimplement
      }
    })
  })
}

// 获取导航栏高度（rpx和px）
function getNavBarHeight() {
  const {
    navBarHeight,
    navBarExtendHeight,
  } = getApp().globalSystemInfo;
  let _pxNavBarHeight = navBarHeight + navBarExtendHeight
  let _winWidth = wx.getSystemInfoSync().windowWidth
  let _ratio = 750 / _winWidth
  let _rpxNavBarHeight = _pxNavBarHeight * _ratio
  return { pxNavBarHeight: _pxNavBarHeight, rpxNavBarHeight: _rpxNavBarHeight, ratio: _ratio }
}

function navigateBack(n = 1) {
  wx.navigateBack({
    delta: n
  })
}

function navigateTo(url) {
  wx.navigateTo({ url: url })
}

// 节流
function throttle(func, wait, options) {
  var timeout, context, args, result;
  var previous = 0;
  if (!options) options = {};

  var later = function () {
    previous = options.leading === false ? 0 : new Date().getTime();
    timeout = null;
    func.apply(context, args);
    if (!timeout) context = args = null;
  };

  var throttled = function () {
    var now = new Date().getTime();
    if (!previous && options.leading === false) previous = now;
    var remaining = wait - (now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = now;
      func.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
  };
  return throttled;
}

// 检查是否登录，没登录跳转至登录页面
function checkCoocaaUserLogin() {
  let _userInfo = wx.getStorageSync('ccUserInfo')
  // 注意用_userInfo == null无效
  if (_userInfo == "") {
    wx.navigateTo({ url: '../login/login' })
  }
}

function getFormatTime(time) { //输入为+new Date()获取的13位时间戳，输出格式化时间 2019-09-10 10:55:03
  let d = new Date(time)
  let digit2 = param => Number(param) < 10 ? ('0' + param) : param
  return `${d.getFullYear()}-${digit2(d.getMonth() + 1)}-${digit2(d.getDate())} ${digit2(d.getHours())}:${digit2(d.getMinutes())}:${digit2(d.getSeconds())}`
}

class VerificationCode { //验证码
  constructor({num = 4} = {}) {
    console.log('constructor')
    this.num = num
  }

  refresh() {
    this._randomStr()
    return this.output
  }

  validate(code ) {
    return this.output.toLowerCase() == code.toLowerCase() ? true : this.refresh()
  }

  _randomStr() {
    let str = 'abcdefghijklmnokprstuvwxyzABCDEFGHIJKLMNOKPRSTUVWXYZ0123456789'
    let output = ''
    let ranNum = () => Math.floor(Math.random() * str.length)
    for(let i of new Array(this.num)) {
      output += str[ranNum()]
    }
    this.output = output
    console.log(output)
  }
}

class CountDown { //倒计时函数
  constructor({time = 60, onProgress, onFinish}) { //onXXX: cb function
    this.time = time
    this.onProgress = onProgress
    this.onFinish = onFinish
    this.timer = null
  }
  start() {
    this.timer = setInterval(() => {
      console.log('count:', this.time)
      typeof this.onProgress == 'function' && this.onProgress(this.time)
      if (this.time-- <= 0) {
        clearInterval(this.timer)
        typeof this.onFinish == 'function' && this.onFinish()
      }
    }, 1000)
  }
  end() {
    if(!!this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  }
}

function getAppLaunchSource() { //获取启动小程序的场景值
  return wx.getLaunchOptionsSync().scene
}

module.exports = {
  showModal_: showModal_,
  showModal: showModal,
  request: request,
  requestP: requestP,
  wxLogin: wxLogin,
  paramsAssemble_tvpai: paramsAssemble_tvpai,
  paramsAssemble_wx: paramsAssemble_wx,
  urlAssemble_tvpai: urlAssemble_tvpai,
  showSuccessToast: showSuccessToast,
  showFailedToast: showFailedToast,
  showLoadingToast: showLoadingToast,
}